package com.beasts.antpage.sh.controller;

import com.beasts.antpage.sh.entity.IntegrateWork;
import com.beasts.antpage.sh.repository.APHomePageRepository;
import com.beasts.antpage.sh.repository.IntegrateWorkRepository;
import com.beasts.antpage.core.utils.HttpClientUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.rpc.ParameterMode;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.xml.sax.InputSource;

/**
 * 获取待办
 * @author cn_zkn
 * @date 07/05/2018 8:39 AM
 * @since 1.0
 */
@Controller
@RequestMapping("/todoWork")
public class GetWorkTaskController {
    @Autowired
    private IntegrateWorkRepository integrateWorkRepository;

    /**
     * 首页初始化待办
     * @return
     */
    @RequestMapping({ "/getWorkTask"})
    @ResponseBody
    public String getWorkTask(HttpServletRequest req) {

        //总的待办数组
        JSONArray  allTodoWorkArray = new JSONArray();
        //从WebService服务中获取的数组-闻政
        allTodoWorkArray.addAll(getWorkFromWebService(req));

        //从Rest服务中获取的数组
        allTodoWorkArray.addAll(getWorkFromAPI(req));



//        //总的待办数组
//        JSONArray  allTodoWorkArray = new JSONArray();
//        //从WebService服务中获取的数组-闻政
//        JSONArray  arrayFromWS = new JSONArray();
//        //从WebService服务中获取的数组-预算
//        JSONArray  arrayFromWS_YS = new JSONArray();
//        //从Rest服务中获取的数组
//        JSONArray  arrayFromRest = new JSONArray();
//
//        arrayFromWS = getWorkFromWebService(req);
//        arrayFromWS_YS = getWorkFromWebService_YS(req);
//        arrayFromRest = getWorkFromRest(req);
//        allTodoWorkArray.addAll(arrayFromWS_YS);
//        allTodoWorkArray.addAll(arrayFromRest);
//        allTodoWorkArray.addAll(arrayFromWS);

        return allTodoWorkArray.toString();
    }

    /*
     *
     * 通过Rest服务获取的待办 例如 久其
     *
     */
//
//    private JSONArray getWorkFromRest(HttpServletRequest req) {
//        //链接地址
//        String url = req.getParameter("JQurl1");
//        if("".equals(url)||url==null){
//            return null;
//        }
//        String userId = req.getParameter("userId");
//        String tokenId = req.getParameter("tokenId");
//        String type = req.getParameter("type");
//
//        url+="userId="+userId;
//        url+="&tokenId="+tokenId;
//        if(type!=null && type!=""){
//            url+="&type="+type;
//        }
//
//        Map<String, String> paramMap = new HashMap<>();
//        String res;
//        try {
//            res = HttpClientUtil.sendPostDataByMap(url, null, "UTF-8", null);
//            if (null == res ||"".equals(res)||"null\r\n".equals(res)) {
//                return null;
//            }
////            String res ="[{\"name\":\"2018年1月《上海市民防办公室》《留存的财政性结转资金情况表》待审核\",\"DataId\":\"D8D345A96648B5EB9CE12C9F4E6C2BDD\",\"FunctionName\":\"2018年1月《上海市民防办公室》《留存的财政性结转资金情况表》待审核\",\"number\":6,\"date\":\"Sun Jun 10 21:50:20 CST 2018\",\"url\":\"192.168.0.90:9797/todoList/C12006,D8D345A96648B5EB9CE12C9F4E6C2BDD\"},{\"name\":\"2018年1月《上海市发展和改革委员会》《留存的财政性结转资金情况表》待审核\",\"DataId\":\"C6840B8E4D5D7A7B09431EEA2AD8F4C1\",\"FunctionName\":\"2018年1月《上海市发展和改革委员会》《留存的财政性结转资金情况表》待审核\",\"number\":6,\"date\":\"Sun Jun 10 20:06:33 CST 2018\",\"url\":\"192.168.0.90:9797/todoList/C12006,C6840B8E4D5D7A7B09431EEA2AD8F4C1\"},{\"name\":\"2018年3月《上海市发展和改革委员会(本级)》《留存的财政性结转资金情况表》待审核\",\"DataId\":\"BBACD679760BF818ACF864B162DDAB3F\",\"FunctionName\":\"2018年3月《上海市发展和改革委员会(本级)》《留存的财政性结转资金情况表》待审核\",\"number\":6,\"date\":\"Wed Mar 21 19:30:55 CST 2018\",\"url\":\"192.168.0.90:9797/todoList/C12006,BBACD679760BF818ACF864B162DDAB3F\"},{\"name\":\"2018年3月《上海市经建处》《留存的财政性结转资金情况表》待上报\",\"DataId\":\"8EE4E0992709B7D07198825C56175181\",\"FunctionName\":\"2018年3月《上海市经建处》《留存的财政性结转资金情况表》待上报\",\"number\":6,\"date\":\"Wed Mar 21 18:08:30 CST 2018\",\"url\":\"192.168.0.90:9797/todoList/C12006,8EE4E0992709B7D07198825C56175181\"},{\"name\":\"2018年4月《上海市经建处》《留存的财政性结转资金情况表》待上报\",\"DataId\":\"8EE0D34123F7FF88258510156ADE645D\",\"FunctionName\":\"2018年4月《上海市经建处》《留存的财政性结转资金情况表》待上报\",\"number\":6,\"date\":\"Fri Mar 02 10:21:05 CST 2018\",\"url\":\"192.168.0.90:9797/todoList/C12006,8EE0D34123F7FF88258510156ADE645D\"},{\"name\":\"2018年2月《上海市经建处》《留存的财政性结转资金情况表》待上报\",\"DataId\":\"8D831D934D9DC4468E52A692F9E0F145\",\"FunctionName\":\"2018年2月《上海市经建处》《留存的财政性结转资金情况表》待上报\",\"number\":6,\"date\":\"Thu Mar 01 16:20:28 CST 2018\",\"url\":\"192.168.0.90:9797/todoList/C12006,8D831D934D9DC4468E52A692F9E0F145\"}]";
//            JSONArray jsonArray = new JSONArray();
//            jsonArray = JSONArray.fromObject(res);
//            return jsonArray;
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//
//    }
//
//    /*
//     *
//     * 通过WebService获取的待办 例如 预算
//     *
//     */
//    private JSONArray getWorkFromWebService_YS(HttpServletRequest req){
//
//        //链接地址
//        String url = req.getParameter("YSurl1");
//        if("".equals(url)||url==null){
//            return null;
//        }
////        String targetNamespace = "http://192.168.0.89:8080/bappr/services/WaitingImplServiceInfo";
//        //方法名
//        String method="getWaitDoTask";
//        //年度
//        String nd = req.getParameter("nd");
//        String userId = req.getParameter("userId");
//        String roleId = req.getParameter("roleId");
//
//        String endpoint = url;
//        Service service = new Service();
//        String result ="";
//        JSONArray localJSONArray = new JSONArray();
//
//        try {
//            Call call = (Call) service.createCall();
//            call.setTargetEndpointAddress(new URL(endpoint));
//            call.setOperationName(method);
//            call.setReturnType(XMLType.XSD_STRING);
//            //若请求的方法需要传入参数则在此添加参数名
//            call.addParameter( "userId", XMLType.XSD_STRING,ParameterMode.IN);
//            call.addParameter( "roleId", XMLType.XSD_STRING,ParameterMode.IN);
//            call.addParameter( "Nd", XMLType.XSD_STRING,ParameterMode.IN);
////            // 设置被调用方法的返回值类型
//            call.setReturnType(XMLType.XSD_STRING);
//            String xml = (String) call.invoke(new Object[] {userId,roleId,nd });
//
//            System.out.print(xml);
//
//            localJSONArray = toJsonArray(xml);
//
//        } catch (Exception e){
//            e.printStackTrace();
//            return null;
//        }
//        return localJSONArray;
//
//    }

    /*
    *
    * 通过WebService获取的待办 例如 闻政
    *
    */
//    private JSONArray getWorkFromWebService(HttpServletRequest req){
//
//        //链接地址
//        String url = req.getParameter("WZurl1");
//        if("".equals(url)||url==null){
//            return null;
//        }
//
////        String targetNamespace = "http://192.168.0.89:8080/bappr/services/WaitingImplServiceInfo";
//        //方法名
//        String method="getString";
//        //年度
//        String nd = req.getParameter("nd");
//        String userId = req.getParameter("userId");
//        String roleId = req.getParameter("roleId");
//
//        String endpoint = url;
//        Service service = new Service();
//        String result ="";
//        JSONArray localJSONArray = new JSONArray();
//
//        try {
//            Call call = (Call) service.createCall();
//            call.setTargetEndpointAddress(new URL(endpoint));
//            call.setOperationName(method);
//            call.setReturnType(XMLType.XSD_STRING);
//            //若请求的方法需要传入参数则在此添加参数名
//            call.addParameter( "userId", XMLType.XSD_STRING,ParameterMode.IN);
//            call.addParameter( "roleId", XMLType.XSD_STRING,ParameterMode.IN);
//            call.addParameter( "Nd", XMLType.XSD_STRING,ParameterMode.IN);
////            // 设置被调用方法的返回值类型
//            call.setReturnType(XMLType.XSD_STRING);
//            String xml = (String) call.invoke(new Object[] {userId,roleId,nd });
////
////            String xml=""
////                    +"<?xml version=\"1.0\" encoding=\"GBK\"?>"
////                    +"<ROOT>"
////                    +"<FUNCTION CODE=\"CZ_PR\" DESCRIPTION=\"绩效系统\">"
////                    +"<MENU>"
////                    +"<URL>jx_url.jsp?year=2017&amp;userid=12640&amp;menuid=900010019</URL>   <NAME>2017绩效申报有待完善的项目</NAME>"
////                    +"<NUMBER>1</NUMBER>"
////                    +"<DATE></DATE>"
////                    +"</MENU>"
////                    +"<MENU>"
////                    +"<URL>jx_url.jsp?year=2017&amp;userid=12640&amp;menuid=900010019</URL>   <NAME>2017绩效申报有待上报的项目</NAME>"
////                    +"<NUMBER>1</NUMBER>"
////                    +"<DATE></DATE>"
////                    +" </MENU>"
////                    +"<MENU>"
////                    +"<URL>jx_url.jsp?year=2017&amp;userid=12640&amp;menuid=900020009</URL>   <NAME>2017绩效跟踪(完整版)有待上报的项目</NAME>"
////                    +"<NUMBER>2</NUMBER>"
////                    +"<DATE></DATE>"
////                    +"  </MENU>"
////                    +"</FUNCTION>"
////
////
////                    +"<FUNCTION CODE=\"CZ_PR\" DESCRIPTION=\"测试系统\">"
////                    +"<MENU>"
////                    +"<URL>jx_url.jsp?year=2017&amp;userid=12640&amp;menuid=900010019</URL>   <NAME>2018绩效申报有待完善的项目</NAME>"
////                    +"<NUMBER>1</NUMBER>"
////                    +"<DATE></DATE>"
////                    +"</MENU>"
////                    +"<MENU>"
////                    +"<URL>jx_url.jsp?year=2017&amp;userid=12640&amp;menuid=900010019</URL>   <NAME>2018绩效申报有待上报的项目</NAME>"
////                    +"<NUMBER>1</NUMBER>"
////                    +"<DATE></DATE>"
////                    +" </MENU>"
////                    +"<MENU>"
////                    +"<URL>jx_url.jsp?year=2017&amp;userid=12640&amp;menuid=900020009</URL>   <NAME>2018绩效跟踪(完整版)有待上报的项目</NAME>"
////                    +"<NUMBER>2</NUMBER>"
////                    +"<DATE></DATE>"
////                    +"  </MENU>"
////                    +"</FUNCTION>"
////
////                    +"<FUNCTION CODE=\"CZ_PR\" DESCRIPTION=\"测试系统2\">"
////                    +"<MENU>"
////                    +"<URL>jx_url.jsp?year=2017&amp;userid=12640&amp;menuid=900010019</URL>   <NAME>2018绩效申报有待完善的项目</NAME>"
////                    +"<NUMBER>1</NUMBER>"
////                    +"<DATE></DATE>"
////                    +"</MENU>"
////                    +"<MENU>"
////                    +"<URL>jx_url.jsp?year=2017&amp;userid=12640&amp;menuid=900010019</URL>   <NAME>2018绩效申报有待上报的项目</NAME>"
////                    +"<NUMBER>1</NUMBER>"
////                    +"<DATE></DATE>"
////                    +" </MENU>"
////                    +"<MENU>"
////                    +"<URL>jx_url.jsp?year=2017&amp;userid=12640&amp;menuid=900020009</URL>   <NAME>2018绩效跟踪(完整版)有待上报的项目</NAME>"
////                    +"<NUMBER>2</NUMBER>"
////                    +"<DATE></DATE>"
////                    +"  </MENU>"
////                    +"</FUNCTION>"
////
////                    +"</ROOT>";
//
//            localJSONArray = toJsonArray(xml);
//
//        } catch (Exception e){
//            e.printStackTrace();
//            return null;
//        }
//        return localJSONArray;
//
//    }

    /*
     *
     * 通过WebService获取的待办
     *
     */
    private JSONArray getWorkFromWebService(HttpServletRequest req){

        //通过webservice 获取待办
        List<IntegrateWork> webServiceList = integrateWorkRepository.queryByWorkTypeAndPortalTypeAndStatus("1","TODOWORK","TODO");
        JSONArray  allTodoWorkArray = new JSONArray();
        for(int i=0;i< webServiceList.size();i++){
            JSONArray  arrayWebServie = getSingleTaskFromWebService(req,webServiceList.get(i));
            allTodoWorkArray.addAll(arrayWebServie);
        }
        return allTodoWorkArray;

    }

    /*
     *
     * 通过WebService获取的单个待办
     *
     */
    private JSONArray getSingleTaskFromWebService(HttpServletRequest req, IntegrateWork integrateWork){


        //链接地址
        String url = integrateWork.getServiceUrl();
        if("".equals(url)||url==null){
            return null;
        }

        //方法名
        String method=integrateWork.getMethodName();

        String endpoint = url;
        Service service = new Service();
        String result ="";
        JSONArray localJSONArray = new JSONArray();

        try {
            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(new URL(endpoint));
            call.setOperationName(method);
            call.setReturnType(XMLType.XSD_STRING);
            //若请求的方法需要传入参数则在此添加参数名
            //参数
            String param = integrateWork.getMethodParams();
            String[] str = param.split(",");
            List searchParams = new ArrayList();

            for(int i=0;i<str.length;i++){
                call.addParameter( str[i].toString(), XMLType.XSD_STRING,ParameterMode.IN);
                searchParams.add(req.getParameter(str[i].toString()));
            }

            // 设置被调用方法的返回值类型
            call.setReturnType(XMLType.XSD_STRING);

            String xml = (String) call.invoke(searchParams.toArray());

            localJSONArray = toJsonArray(xml);

        } catch (Exception e){
            e.printStackTrace();
            return null;
        }
        return localJSONArray;

    }



    /*
     *
     * 通过API获取的待办
     *
     */
    private JSONArray getWorkFromAPI(HttpServletRequest req){

        //通过webservice 获取待办
        List<IntegrateWork> apiList = integrateWorkRepository.queryByWorkTypeAndPortalTypeAndStatus("0","TODOWORK","TODO");
        JSONArray  allTodoWorkArray = new JSONArray();
        for(int i=0;i< apiList.size();i++){
            JSONArray  arrayAPI = getSingleTaskFromAPI(req,apiList.get(i));
            allTodoWorkArray.addAll(arrayAPI);
        }
        return allTodoWorkArray;

    }
    /*
     *
     * 通过API获取的单个待办
     *
     */
    private JSONArray getSingleTaskFromAPI(HttpServletRequest req, IntegrateWork integrateWork){

        //链接地址
        String url = integrateWork.getServiceUrl();
        if("".equals(url)||url==null){
            return null;
        }

        //参数
        String param = integrateWork.getMethodParams();
        String[] str = param.split(",");

        for(int i=0;i<str.length;i++){
            url+="&"+str[i]+"=";
            url+=req.getParameter(str[i]).toString();
        }

        Map<String, String> paramMap = new HashMap<>();
        String res;
        try {
            res = HttpClientUtil.sendPostDataByMap(url, null, "UTF-8", null);
            if (null == res ||"".equals(res)||"null\r\n".equals(res)) {
                return null;
            }
            JSONArray jsonArray = new JSONArray();
            jsonArray = JSONArray.fromObject(res);
            return jsonArray;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }



    private JSONArray toJsonArray(String xml) {

        JSONArray localJSONArray = new JSONArray();
        try {
            if (xml != null) {
                StringReader localStringReader = new StringReader(xml);
                InputSource localInputSource = new InputSource(localStringReader);
                SAXReader localSAXReader = new SAXReader();
                Document localDocument = localSAXReader.read(localInputSource);
                Element localElement1 = localDocument.getRootElement();
                List localList1 = localElement1.elements();
                for (int i = 0; i < localList1.size(); i++) {
                    Element localElement2 = (Element) localList1.get(i);
                    String str1 = localElement2.attributeValue("NAME");
                    String str2 = localElement2.attributeValue("DESCRIPTION");
                    List localList2 = localElement2.elements();
                    for (int j = 0; j < localList2.size(); j++) {
                        Element localElement3 = (Element) localList2.get(j);
                        String str3 = localElement3.elementTextTrim("URL");
                        String str4 = localElement3.elementTextTrim("NAME");
                        if ((str4 != null) && (!"".equals(str4))) {
                            String str5 = localElement3.elementTextTrim("NUMBER");
                            String str6 = localElement3.elementTextTrim("DATE");
                            JSONObject localJSONObject = new JSONObject();
                            localJSONObject.put("name", str4);
                            localJSONObject.put("DataId", "func" + i);
                            localJSONObject.put("FunctionName", str2);
                            localJSONObject.put("number", str5);
                            localJSONObject.put("date", str6);
                            localJSONObject.put("url", str3);
//                            localJSONObject.put("funcId", "func" + i);
//                            localJSONObject.put("menuSize", localList2.size());
//                            localJSONObject.put("funcDesc", str2);
                            localJSONArray.add(localJSONObject);

                        }
                    }
                }

            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return localJSONArray;
    }

}
